#!/bin/sh

#
# Test that delta firmware updates give meaningful progress reports
#
# brew install xdelta
#

. "$(cd "$(dirname "$0")" && pwd)/common.sh"
create_15M_file

FWFILE2="$WORK/fwup2.fw"

cat >"$CONFIG" <<EOF
define(ROOTFS_A_PART_OFFSET, 0)
define(ROOTFS_A_PART_COUNT, 32768)
define(ROOTFS_B_PART_OFFSET, 32768)
define(ROOTFS_B_PART_COUNT, 32768)

file-resource rootfs {
        host-path = "${TESTFILE_15M}"
}

task complete {
    on-resource rootfs { raw_write(\${ROOTFS_A_PART_OFFSET}) }
}
task upgrade {
    on-resource rootfs {
        delta-source-raw-offset=\${ROOTFS_A_PART_OFFSET}
        delta-source-raw-count=\${ROOTFS_A_PART_COUNT}
        raw_write(\${ROOTFS_B_PART_OFFSET})
    }
}
EOF

# Create the firmware file, then "burn it"
$FWUP_CREATE -c -f "$CONFIG" -o "$FWFILE"
$FWUP_APPLY -a -d "$IMGFILE" -i "$FWFILE" -t complete

# Manually create the delta upgrade by replacing rootfs.next
# with the delta3 version
mkdir -p "$WORK/data"
xdelta3 -A -S -f -s "$TESTFILE_15M" "$TESTFILE_15M" "$WORK/data/rootfs"
cp "$FWFILE" "$FWFILE2"
(cd "$WORK" && zip "$FWFILE2" data/rootfs)

$FWUP_APPLY -a -n -d "$IMGFILE" -i "$FWFILE2" -t upgrade > "$WORK/actual_output.txt"

# Without the xdelta3 progress reporting fix, the output is:
# 0
# 55
# 99
# 100
# With the xdelta3 progress reporting fix, the output is:
cat >"$WORK/expected_output.txt" <<EOF
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
EOF
diff -w "$WORK/expected_output.txt" "$WORK/actual_output.txt"

# Check that the verify logic works on both files
$FWUP_VERIFY -V -i "$FWFILE"
$FWUP_VERIFY -V -i "$FWFILE2"
